package com.jkkc.lib.base.util

import android.app.Application
import android.speech.tts.TextToSpeech
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jkkc.lib.base.extend.BUS_INIT_TTS_FAIL
import com.jkkc.lib.base.extend.NUM_TEN
import java.util.*

/**
 * Description:
 */
object SystemTTS {

    private lateinit var mApp: Application
    private var mTextToSpeech: TextToSpeech? = null

    /**
     * 是否支持TTS
     */
    private var isSupport = true

    /**
     * TTS是否初始化成功
     */
    private var isInitSuccess = false

    /**
     * 初始化次数
     */
    private var initCount = 0

    /**
     * 最后一次未播放的内容
     */
    private var mTempText = ""

    /**
     * 讯飞语音引擎
     */
    private const val DEFAULT_TTS_ENGINE = "com.iflytek.speechcloud"

    fun initTTS(application: Application) {
        initTTS(application, DEFAULT_TTS_ENGINE)
    }

    /**
     * 初始化语音合成
     *
     * @param application 上下文
     * @param engine 语音合成引擎
     */
    fun initTTS(application: Application, engine: String) {
        initCount++
        mApp = application
        destroyTTS()
        mTextToSpeech = TextToSpeech(mApp, { statue ->
            if (statue == TextToSpeech.SUCCESS) {
                // 设置音调,值越大声音越尖（女生），值越小则变成男声,1.0是常规
                mTextToSpeech?.setPitch(1.0F)
                // 设定语速,默认1.0正常语速
                mTextToSpeech?.setSpeechRate(1.5F)
                //设置语言
                mTextToSpeech?.language = Locale.CHINESE
                val result = mTextToSpeech?.setLanguage(Locale.CHINA)
                isSupport = !(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
                isInitSuccess = true
                playLastContent()
            } else {
                isInitSuccess = false
                if (initCount > NUM_TEN) {
                    LiveEventBus.get(BUS_INIT_TTS_FAIL, String::class.java).post("")
                } else {
                    initTTS(mApp)
                }
            }
        }, engine)
    }

    /**
     * 获取安装的语音引擎
     */
    fun getEngineList(): List<TextToSpeech.EngineInfo> = mTextToSpeech?.engines ?: mutableListOf()

    fun getIsInitSuccess(): Boolean = isInitSuccess

    /**
     * 播放最后一次播放失败的内容
     */
    private fun playLastContent() {
        if (mTempText.isNotEmpty()) {
            play(mTempText)
            mTempText = ""
        }
    }

    @JvmStatic
    fun play(text: String?) {
        if (!isSupport) {
            ToastUtils.showShort("系统不支持语音合成")
            return
        }
        if (text.isNullOrEmpty()) {
            ToastUtils.showShort("播放内容不能为空")
            return
        }
        if (isInitSuccess) {
            val result = mTextToSpeech?.speak(text, TextToSpeech.QUEUE_ADD, null, null)
            if (result == TextToSpeech.ERROR) {
                mTempText = text
                initTTS(mApp)
            }
        } else {
            initTTS(mApp)
        }
    }

    /**
     * 不管是否正在朗读TTS都被打断
     */
    @JvmStatic
    fun stopTTS() {
        mTextToSpeech?.stop()
    }

    /**
     * 关闭，释放资源
     */
    @JvmStatic
    fun destroyTTS() {
        try {
            stopTTS()
            mTextToSpeech?.shutdown()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}